package org.nicocube.airain.utils.telnet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CommandInterpreter implements Runnable {
	private static final Logger log = LoggerFactory.getLogger(CommandInterpreter.class); 
	
	private TelnetServer telnetServer;
	private CommandBinder commandBinder;
	private NetworkConnection networkConnection;

	public CommandInterpreter(TelnetServer telnetServer, CommandBinder commandBinder, NetworkConnection networkConnection) {
		this.telnetServer = telnetServer;
		this.commandBinder = commandBinder;
		this.networkConnection = networkConnection;
	}

	@Override
	public void run() {
		if (log.isDebugEnabled()) log.debug("New Telnet connection opened...");
		String command = null;
		try {
			while(!telnetServer.isStopped()){
				if (log.isDebugEnabled()) log.debug("prompting..."); 
				command = networkConnection.prompt();
				if (log.isDebugEnabled()) log.debug("command : "+command); 
				try {
					networkConnection.sendLine(commandBinder.process(command));
				} catch (UnknowCommandException e) {
					networkConnection.sendLine("> "+e.getMessage());
				} catch (EndingCommandException e) {
					telnetServer.stop();
					break;
				}
			}
		}
		catch (Exception e) {
			log.error("Error while processing commands", e);
		}
		finally {
			try {
				if (networkConnection != null)
					networkConnection.disconnect();
			}
			catch (Exception e) {
				log.warn("Error on closing connection ", e);
			}
		}
		if (log.isDebugEnabled()) log.debug("Connection closed");
	}

}
